package com.my.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

	Logger logger = Logger.getLogger(SpringTestController.class);

	@RequestMapping("/upload_file_page")
	public String uploadFilePage() {
		return "/upload_file_page";
	}

	@RequestMapping("/upload_file")
	public void uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
		InputStream in = null;
		OutputStream ou = null;
		try {
			/*
			 * File destFile = new File("E:\\" + file.getOriginalFilename()); in
			 * = file.getInputStream(); ou = new FileOutputStream(destFile);
			 * byte[] buffer = new byte[8024]; int length = 0; while ((length =
			 * in.read(buffer)) != -1) { ou.write(buffer, 0, length); }
			 * in.close(); ou.close();
			 */
			// 更简易的方法
			File destFile = new File("E:\\" + file.getOriginalFilename());
			file.transferTo(destFile);

		} catch (Exception e) {
			logger.error(e);
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
			if (null != ou) {
				try {
					ou.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
		}
	}
}
